Online-Academy
Look, Read, Understand, Apply

Exception Handling


def multiply(a, b):
    try:
        return a * b
    except TypeError:
        return "Type Error: Unsupported operand types."

def safe_divide(a, b):
    if not isinstance(a, (int, float)) or not isinstance(b, (int, float)):
        print("Inputs must be numbers.")
        return
    print(a / b)


if __name__== "__main__":
    try:
        a = 10
        b = "5"
        result = a + b
        print(result)
    except TypeError:
        print("Type Error: Cannot add an integer and a string.")
 
    try:
        num1 = int(input("Enter first number: "))
        num2 = int(input("Enter second number: "))
        print(num1 + num2)
    except TypeError:
        print("Type Error occurred.")
    except ValueError:
        print("Invalid input! Please enter numbers only.")
   
    print(multiply(5, "hello"))
    
    try:
        data = [1, 2, 3]
        print(data + 4)
    except TypeError as e:
        print("Type Error occurred:", e)

    safe_divide(10, "2")